
import com.peersafe.chainsql.core.Chainsql;
import com.peersafe.chainsql.core.Submit.SyncCond;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.CountDownLatch;


import org.json.JSONObject;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;

public class Chain {
	public static final Chainsql c= Chainsql.c;
	public static long beginTm=0;
	public static String tbName = "mgsjsql";	
	public static String account_id = "raJ3ti7h82oG9gi3RYwbWWB42WsnubLabo";  //jsonAddr.getString("account_id");
	public static String secret = "shMZ3HTU1eCqTYtVNnD89FABsqqRq";  //jsonAddr.getString("secret");
	
	
	@Before
	public void init() {
		System.out.println("============================开始===========================");
		beginTm = System.currentTimeMillis();
		c.connect("ws://192.168.0.221:6006");		
		System.out.println("=================================");
		System.out.println("表名："+tbName);
		System.out.println(account_id+"\n"+secret);
		System.out.println("=================================");				
		c.as(account_id,secret);
	}
	
	
	
	
	
//	@After
	public void end() {
		System.out.println("所用时间：" + (System.currentTimeMillis() - beginTm) + "ms");
		System.out.println("==================结束==================");
	}
	
	
	public void addAccout(){
		JSONObject jsonAddr=c.generateAddress();  
		System.out.println(jsonAddr);		
		String account_id = jsonAddr.getString("account_id");
		String secret =jsonAddr.getString("secret");
		System.out.println("=====================添加账户============================");
		System.out.println(account_id+"\n"+secret);
		System.out.println("=======================================================");	
		pay(account_id);
		
	}
	
	
	public  void pay(String account_id) {
			String address = account_id;
	        c.as("rHb9CJAWyB4rj91VRWn96DkukG4bwdtyTh", "snoPBrXtMeMyMHUVTgbuqAfg1SUTb");	//	c.use(account_id);
		    JSONObject js00 = c.pay(address,"200");
			System.out.println("======================pay测试=========================\n");
			System.out.println(js00);
			System.out.println("转账成功："+address);
			System.out.println("\n======================================================");
	}
	
	
	public  void create() {				 
		 	JSONObject js01 = c.createTable(tbName,c.array(
		 			"{'field':'id','type':'int','length':11,'PK':1,'NN':1,'UQ':1,'AI':1}",
					"{'field':'consql','type':'varchar','length':600}",
					"{'field':'sqluser','type':'varchar','length':50}",
					"{'field':'OBJ_NAME','type':'varchar','length':200}",
					"{'field':'sjnumber','type':'int','length':16}",
					"{'field':'dycs','type':'int','length':10}",
					"{'field':'czsj','type':'datetime','length':20}"
					)).submit(SyncCond.db_success);	
			System.out.println("===================create测试===================\n");
			System.out.println(js01.get("status")+"\n"+js01);
			System.out.println("\n================================================");		
	}
	
	
	
	public  void insert() {		
		String sql="{"    
				//+ 'id':'10',"+
				+ "'consql':'select',"
				+ "'sqluser':'scott',"
				+ "'sjnumber':100,"
				+ "'dycs':1,"
				+ "'czsj':'2017/11/6 11:03:08'"
				+ "}";
/*		List<String>  as=new ArrayList<String>();   //c.array("{'id':'10','name':'peers','age':'2'}")		
		as.add(sql);		
	  	System.out.println(as);  
	  	JSONObject js02 = c.table(tbName).insert(as).submit(SyncCond.db_success); */
		JSONObject js02 = c.table(tbName).insert(Chainsql.array(sql)).submit(SyncCond.db_success);
		System.out.println("===================insert测试=====================\n");		
		System.out.println(js02);
		System.out.println("\n===================================================");

	}
	
	@Test
	public  void select() {		
	    JSONObject js01 = c.table(tbName).get(c.array("")).submit(SyncCond.db_success); //.limit("{'total':10}")
	  //  JSONObject js02 = c.table(tbName).get(c.array("{'id':'1'}")).withFields("['name','age']").submit(SyncCond.db_success);
		System.out.println(" ===================select测试=====================\n");	
		System.out.println(js01);
		//System.out.println(js02);
		System.out.println("\n===================================================");
	}
	
	
	public void drop(){
		JSONObject js0 = c.dropTable(tbName).submit(SyncCond.db_success);
		System.out.println("=======================drop测试=======================\n");
		System.out.println(js0);
		System.out.println("\n======================================================"); 
		
	}
	
	public void update(){		
		JSONObject js01 = c.table(tbName).get(c.array("{'Dycs': 0}")).update(c.array("{'age':52,'name':'lisi'}")).submit(SyncCond.db_success);
		System.out.println(" ===================update测试=====================\n");	
		System.out.println(js01);
		System.out.println("\n===================================================");
		
	}
	
	
	public void delete(){
		JSONObject js01 = c.table(tbName).get(c.array("{'sjnumber': 0}")).delete().submit(SyncCond.db_success);
			System.out.println(" ===================delete测试=====================\n");	
			System.out.println(js01);
			System.out.println("\n===================================================");
	}
	
	public void rename(){
		String temp="tempName";
		JSONObject js0 = c.renameTable(tbName,temp).submit();		
		tbName=temp;
		System.out.println("=========================rename测试=====================\n");
		System.out.println(js0);
		System.out.println("表名更改为："+tbName);
		System.out.println("\n========================================================"); 
		
	}
	
	
	public void testFunction(){
		int ThreadNum=600;  
		 final CountDownLatch cdl= new CountDownLatch(ThreadNum);
	        long starttime=System.currentTimeMillis();
	        for(int k=1;k<=ThreadNum;k++){
	        	Thread thread=new Thread(new MyExecute(k,cdl));
	        	thread.start();
	        }        
	        try {
	            cdl.await();
	            long spendtime=System.currentTimeMillis()-starttime;
	            System.out.println( ThreadNum+"个线程花费时间:"+Util.formatTime(spendtime));            
	        } catch (InterruptedException e) {
	            e.printStackTrace();
	        }
	}
	
}


class MyExecute implements Runnable {
	 private int name;  //线程编号
	 CountDownLatch cdl; //线程实例	
     long starttime; 	
	 public MyExecute(int name,CountDownLatch cdl) {
	  this.name = name;
	  this.cdl= cdl;	 
	 }
	 @Override
    public void run() {
    	try {    		
    		//执行操作
    		SimpleDateFormat time=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss:SSS");
    		String TimeString = time.format(new java.util.Date());
   		System.out.println("线程"+name+"执行的操作 "+TimeString);		    
   		Thread.sleep(2000);
   		 TimeString = time.format(new java.util.Date());
   		System.out.println("线程"+name+"执行的操作 "+TimeString);		    
    		cdl.countDown();
			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
    } 
}